package com.ruoyi.project.remoteControl.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.remoteControl.service.RemoteControlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 接收前端请求，向被控端发起远控或者结束远控
 */
@RestController
public class RemoteControlController {
    @Autowired
    RemoteControlService remoteControlService;

    /**
     * 通过MQTT发起远控
     * @param deviceClientId
     * @return
     */
    @PostMapping("remoteControl/install")
    public AjaxResult installService(@RequestBody String deviceClientId){
        // 若远控发起成功，则jsonObject为生成的远控会话信息并被返回给前端；发起失败时，jsonObject为null
        JSONObject jsonObject = remoteControlService.mqttRemoteConnect(deviceClientId);
        System.out.println(jsonObject);
        if (jsonObject!=null){
            return AjaxResult.success(jsonObject);
        }else{
            return AjaxResult.error("远控发起失败！可能原因：网络请求超时/目标主机已离线");
        }
    }

    /**
     * 通过MQTT结束远控
     * @param deviceClientId
     * @return
     */
    @PostMapping("remoteControl/uninstall")
    public AjaxResult uninstallService(@RequestBody String deviceClientId){
        // 若远控结束成功，则result字符串中将包含“远控服务注销成功”
        String result = remoteControlService.mqttRemoteDisconnect(deviceClientId);
        System.out.println(result);
        if (result.contains("成功")){
            return AjaxResult.success(result);
        }else{
            return AjaxResult.error("远控断开失败！可能原因：网络请求超时/目标主机已离线");
        }
    }

    /**
     * 通过后端方法调用浏览器打开远控url
     * @param deviceClientId
     */
    @PostMapping("remoteControl/openWeb")
    public void openWeb(@RequestBody String deviceClientId){
        remoteControlService.openRemoteHtml(deviceClientId);
    }
    
}
